package com.demo.service;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.demo.listener.ExcelBatchImportListener;
import com.demo.mapper.UserMapper;
import com.demo.pojo.User;
import com.demo.pojo.UserExcel;
import com.demo.util.EasyExcelUtils;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;

@Slf4j
@Service
public class UserService {

    @Autowired
    public UserMapper userMapper;


    public List<User> findByName(String name) {
       return userMapper.findUserByName(name);
    }

    public User insertUser(User user) {
        userMapper.insertUser(user);
        return user;
    }

    public IPage<User> ListUser(IPage<User> page) {
        return userMapper.ListUser(page);
    }


    public int Update(User user) {
        return userMapper.Update(user);
    }

    public int delete(int id) {
        return userMapper.delete(id);
    }


    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void upload(InputStream inputStream) {
        String downloadUrl = Strings.EMPTY;
        try {
            List<UserExcel> list = Lists.newArrayList();
            StringBuilder stringBuilder = new StringBuilder();
            EasyExcelUtils.readExcelOnce(inputStream, UserExcel.class,
                    new ExcelBatchImportListener(list, stringBuilder, userMapper));
            // 如果有异常信息，则输出文件

        } catch (Exception e) {
            log.error("上传项目权限异常", e);

        }

    }

    public List<User> findUser() {
        return userMapper.findUser();
    }

    public User insert(String userName) {
        User user = new User();
        user.setName(userName);
        userMapper.insertUser(user);
        return user;
    }
}